<template>
  <view>
    <view style="height: 90vh">
      <image class="bindbakcImage" mode="scaleToFill" :src="'https://zsbm.dyedu.net/xsbmFile/api/common/file/show/20220001/e857699567364d2abc37b675e85ab784'+getFileSignParams()" />
    </view>
    <zlb-footer></zlb-footer>
  </view>
</template>

<script lang="ts" setup>
import { onBeforeMount, onBeforeUnmount, onMounted, reactive } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import systemConfig from '@/common/config';
import { getFileSignParams } from '@/common/utils/signatureUtil';
import { system, user } from '@/store';
import * as util from '@/common/utils/util';
import * as u from '@/tool/function/util';
//-----内部参数----------------
const data = reactive({
  createdTime: new Date().getTime(),
  beforeMountTime: 0,
  mountedTime: 0,
  userType: '1',
  browserType: '',
  zlbToken: '',
  checkinTime: null,
  checkoutTime: null,
  gotoUrl: systemConfig.homePath,
});
let zwlog: any = null;
//---------------------初始化----------------------------------------------
onShow(() => {
  system.setZlbFlag(true);
  system.setShowNavBar(false);
  util.getZlbUiStyle();
});
onLoad((option: any) => {
  if (option.redirect) {
    data.gotoUrl = decodeURIComponent(option.redirect);
  }
  system.setZlbFlag(true);
  system.setShowNavBar(false);
  user.setTokenByZlb(null,null)
  login(option);
});
onBeforeMount(() => {
  data.beforeMountTime = new Date().getTime();
});
onMounted(() => {
  data.mountedTime = new Date().getTime();
});
onBeforeUnmount(() => {
  let beforeDestroyTime = new Date().getTime();
  if (zwlog) {
    zwlog.onReady(function () {
      zwlog.sendPV({
        miniAppId: systemConfig.zlbAppId, //IRS 服务侧应用 appid
        Page_duration: beforeDestroyTime - data.createdTime, //用户从进入到离开当前页面的时长 生命周期beforeDestroy - created
        t2: data.beforeMountTime - data.createdTime, //页面启动到加载完成的时间     生命周期beforeMount - created
        t0: data.mountedTime - data.createdTime, //页面启动到页面响应完成的时间 生命周期mounted - created
        log_status: systemConfig.zlbAppId, //IRS 服务侧应用 appid
      });
    });
  }
});
//-----------------方法区--------------------------------
const login = async (option: any) => {
  let sp = '';
  if (option.sp) {
    sp = option.sp;
  } else {
    sp = util.getQueryString('sp');
  }
  if (sp) {
    data.gotoUrl = decodeURIComponent(sp);
  }
  let ticketId = '';
  let ticket = '';
 /* if (option.ticket) {
    ticket = option.ticket;
  } else {
    ticket = util.getQueryString('ticket');
  }*/

  let browerInfo:any = system.browerInfo;
  if (!browerInfo || !browerInfo.browserType) {
    browerInfo = util.getBrowerInfo();
    system.setBrowerInfo(browerInfo);
  }
  let type = '';
  if (browerInfo) {
    type = browerInfo.browserType;
  }
  if (ZWJSBridge.ssoTicket) {
    const ssoFlag = await ZWJSBridge.ssoTicket({});
    if (ssoFlag && ssoFlag.result === true) {
      //使用 IRS“浙里办”单点登录组件
      if (ssoFlag.ticketId) {
        ticketId = ssoFlag.ticketId;
        let stdata = { st: '',loginAppId:systemConfig.appId };
        stdata.st = ticketId;
        //微信小程序
        //根据ticketId 获取浙里办 token
        await $api.common.send
            .postCrypto('zlb0004', stdata)
            .then(async (res: any) => {
              zwlog = new ZwLog({
                _user_id: res.result.personInfo.userId,
                _user_nick: res.result.personInfo.userName,
              });
              data.zlbToken = res.result.zlbToken;
              let accessToken = res.result.accessToken;
              let refreshToken = res.result.refreshToken;
              await user.setTokenByZlb(accessToken,refreshToken);
              if(res.result.secretKey){
                u.setCookie('USERSECRET',util.encryptSM4(JSON.stringify(res.result.secretKey),system.defaultSM4Key));
              }
              await user.setUserSecret(res.result.secretKey);
              const sessionData = {};
              let sessionFlag = await $api.common.getUserInfoEn.post(sessionData);
              if (!sessionFlag) {
                if (!systemConfig.loginErrorPath) {
                  uni.showToast({
                    title: '登录异常页面路径不能配置为空',
                    icon: 'none',
                  });
                  return;
                }
                let queryData = { errorMsg: '获取用户信息失败' };
                $router.replaceAll(systemConfig.loginErrorPath, queryData);
              } else {
                gotoSuccess();
              }
            })
            .catch((error) => {
              getZlbTokenError({ error: error, ticket: ticketId });
            });
        return;
      } else {
        //当“浙里办”单点登录失败或登录态失效时调用 ZWJSBridge.openLink 方法重 新获取 ticketId。
        ZWJSBridge.openLink({ type: 'reload' }).then((res) => {
          ticketId = res.ticketId;
        });
      }
    } else {
      console.log('使用 IRS【个人/法人单点登录】组件-2');
      //使用 IRS【个人/法人单点登录】组件
      loginComponent({ flag: '2', type: type });
    }
  } else {
    console.log('使用 IRS【个人/法人单点登录】组件-1');
    //使用 IRS【个人/法人单点登录】组件
    loginComponent({ flag: '1', type: type });
  }
};
const getZlbTokenError = ({ error, ticket }: { error: any; ticket: any }) => {
  let errorMsg = '';
  if (error.message) {
    errorMsg = '浙里办票据认证异常:' + error.message + ticket;
  } else {
    if (error) {
      errorMsg = '浙里办票据认证异常:' + JSON.stringify(error) + ticket;
    } else {
      errorMsg = '浙里办票据认证异常' + ticket;
    }
  }
  console.log(errorMsg);
  uni.showToast({
    title: errorMsg,
    icon: 'none',
  });
  return;
};
const loginComponent = ({ flag, type }: { flag: any; type: any }) => {
  console.log('原始地址2：', window.location.href);
  if ((type = 'zlb')) {
    window.location.replace('https://puser.zjzwfw.gov.cn/sso/mobile.do?action=oauth&scope=1&servicecode=' + systemConfig.zlbCode + '&goto=' + encodeURIComponent(data.gotoUrl));
  } else {
    window.location.replace('https://puser.zjzwfw.gov.cn/sso/alipay.do?action=ssoLogin&servicecode=' + systemConfig.zlbCode + '&goto=' + encodeURIComponent(data.gotoUrl));
  }
};
const gotoSuccess = () => {
  let url = data.gotoUrl;
  console.log('跳转页面' + data.gotoUrl);
  if (url) {
    if (url == systemConfig.homePath) {
      if (systemConfig.tabBarModel === 'uni') {
        uni.switchTab({ url: systemConfig.homePath });
      } else {
        $router.replaceAll(systemConfig.homePath, {});
      }
    } else {
      $router.replaceAll(url, {});
    }
  } else {
    if (systemConfig.tabBarModel === 'uni') {
      uni.switchTab({ url: systemConfig.homePath });
    } else {
      $router.replaceAll(systemConfig.homePath, {});
    }
  }
};
window.addEventListener(
  'pageshow',
  function (event) {
    console.log('this way ');
    let browerInfo :any = system.browerInfo;
    if (!browerInfo) {
      browerInfo = util.getBrowerInfo();
    }
    let type = '';
    if (browerInfo) {
      type = browerInfo.browserType;
    }

    if (event.persisted || (window.performance && window.performance.navigation.type == 2)) {
      console.log('window.performance.navigation.type: ' + window.performance.navigation.type);
      console.log('type: ' + type);
      if (type != 'weixin') {
        if (ZWJSBridge) {
          try {
            ZWJSBridge.close()
              .then((result: any) => {
                console.log(result);
              })
              .catch((error: any) => {
                console.log(error);
              });
          } catch (e) {}
        }
      }
      if (AlipayJSBridge) {
        try {
          AlipayJSBridge.call('closeWebview');
        } catch (e) {
          console.log(e);
        }
      }
    }
  },
  false
);
</script>

<style lang="scss" scoped>
.bindbakcImage {
  width: 100%;
  height: 90vh;
  position: absolute;
  top: 0;
  left: 0;
}
</style>
